package com.juxing.sdk.util;

import java.util.concurrent.ThreadLocalRandom;

import com.juxing.sdk.SdkException;

/**
 * 随机相关工具类
 * @author liu.qingliang
 *
 */
public class RandUtil {

	private static final int[] RAND_NUMS = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
	
	private final static char[] SUPER_WORDS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
	private final static char[] LOWER_WORDS = "abcdefghijklmnopqrstuvwxyz".toCharArray();
	private final static char[] WORDS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
	private final static char[] MIX_WORDS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
	
	private static final int  TYPE_WORDS = 2;
	private static final int  TYPE_LOWER_WORDS = 3;
	private static final int  TYPE_SUPER_WORDS = 4;
	private static final int  TYPE_MIX_WORDS = 5;
	
	
	/**
	 * 获取4位随机数
	 * @return
	 */
	public static int getRandNum4() {
		return getRandNum(4);
	}
	/**
	 * 获取6位随机数
	 * @return
	 */
	public static int getRandNum6() {
		return getRandNum(6);
	}
	/**
	 * 获取8位随机数
	 * @return
	 */
	public static int getRandNum8() {
		return getRandNum(4);
	}
	/**
	 * 获取n位随机数
	 * @param n 随机数的位数（如5，则表示[10000，99999]）
	 * @return
	 */
	public static int getRandNum(int n) {
		if(n <= 0) {
			return 0;
		} else if(n == 1) {
			return ThreadLocalRandom.current().nextInt(10);
		} else if(n == 10) {
			return 1000000000 + getRandNum(9);
		} else if(n > 10) {
			throw new SdkException("invalid parameter n(n must <= 10)");
		}
		int r = RAND_NUMS[n - 1] + ThreadLocalRandom.current().nextInt(RAND_NUMS[n] - RAND_NUMS[n - 1]);
		return r;
	}
	/**
	 * 随机获取n位小写英文组成的字符串
	 * @param n
	 * @return
	 */
	public static String getRandLowerLetter(int n){
		return getRand(n, TYPE_LOWER_WORDS);
	}
	/**
	 * 随机获取n位大写英文组成的字符串
	 * @param n
	 * @return
	 */
	public static String getRandUpperLetter(int n){
		return getRand(n, TYPE_SUPER_WORDS);
	}
	
	/**
	 * 随机获取n位英文字母组成的字符串
	 * @param n
	 * @return
	 */
	public static String getRandLetter(int n){
		return getRand(n, TYPE_WORDS);
	}
	
	/**
	 * 随机获取n位英文字母或数字组成的字符串
	 * @param n
	 * @return
	 */
	public static String getRandString(int n){
		return getRand(n, TYPE_MIX_WORDS);
	}
	
	/**
	 * 
	 * @param n 生成随机字符串的位数
	 * @param type 生成随机字符串的类型
	 * @return
	 */
	public static String getRand(int n,int type){
		StringBuilder result = new StringBuilder();
		char[] ch = getCh(type);
		if(ch != null && n > 0){
			for (int i = 0; i < n; i++) {
				result.append(ch[ThreadLocalRandom.current().nextInt(ch.length)]);
			}
		}
		return result.toString();
	}
	
	private static char[] getCh(int type) {
		switch(type) {
		case TYPE_WORDS:
			return WORDS;
		case TYPE_LOWER_WORDS:
			return LOWER_WORDS;
		case TYPE_SUPER_WORDS:
			return SUPER_WORDS;
		case TYPE_MIX_WORDS:
			return MIX_WORDS;
		default:
			throw new SdkException("invalid parameter type");
		}
	}
	
}
